<template>
  <div class="app-container">
    <vxe-split class="content" border vertical>
      <vxe-split-pane height="35%">
        <WorkOrder
          ref="formRef"
          wo-type="涂布"
          :form-data-update="formData"
          :equipment-options-update="equipmentOptions"
          :team-options-update="teamOptions"
        />
      </vxe-split-pane>
      <vxe-split-pane height="55%">
        <vxe-tabs
          v-model="activeTab"
          style="height: 100%"
          destroyOnClose="false"
        >
          <vxe-tab-pane title="子卷信息" name="1">
            <WoSub
              ref="gridRef3"
              :wo-raw-sub="woRawSub"
              :form-data="formData"
            />
          </vxe-tab-pane>
          <vxe-tab-pane title="原材料信息" name="2">
            <WoRaw
              :wo-raw-sub="woRawSub"
              :form-data="formData"
              ref="gridRef2"
              wo-type="涂布"
            >
            </WoRaw>
          </vxe-tab-pane>
          <vxe-tab-pane title="缺陷记录" name="3">
            <WoSubFault />
          </vxe-tab-pane>
          <vxe-tab-pane title="参数采集" name="4">
            <wo-tag-value ref="gridRef4" />
          </vxe-tab-pane>
        </vxe-tabs>
      </vxe-split-pane>
      <vxe-split-pane height="10%">
        <vxe-button
          status="primary"
          content="开工"
          @click="startWoRawClick"
        ></vxe-button>
        <vxe-button status="success" content="暂停"></vxe-button>
        <vxe-button
          status="info"
          content="完工"
          @click="endWoRawClick"
        ></vxe-button>
        <vxe-button status="warning" content="标签打印"></vxe-button>

        <vxe-button
          content="裁切信号"
          status="error"
          @click="parameterAcquisition"
        ></vxe-button>
      </vxe-split-pane>

      <!-- <vxe-split-pane>
        <div style="height: 33%; background-color: #d8d8f9">底部</div>
      </vxe-split-pane> -->
    </vxe-split>
    <vxe-modal v-model="showPopup" v-bind="modalOptions" :loading="loading">
      <template #default>
        <vxe-form
          v-bind="formOptions"
          @submit="submitEvent"
          @reset="resetEvent"
        ></vxe-form>
      </template>
    </vxe-modal>

    <!--修改状态记录-->
    <vxe-modal v-model="showPopup2" v-bind="modalOptions2" :loading="loading">
      <template #default>
        <vxe-form
          v-bind="formOptions2"
          @submit="submitEvent2"
          @reset="resetEvent"
        ></vxe-form>
      </template>
    </vxe-modal>
    <!--缺陷记录-->
    <vxe-modal v-model="showPopup3" v-bind="modalOptions3" :loading="loading">
      <template #default>
        <vxe-form
          v-bind="formOptions3"
          @submit="submitEvent3"
          @reset="resetEvent"
        ></vxe-form>
      </template>
    </vxe-modal>
  </div>
</template>
<script>
import { VxeUI } from "vxe-pc-ui";
import {
  getWorkOrderByPage,
  addWorkOrder,
  delWorkOrder,
  getWorkOrderByCode,
} from "@/api/product/workOrder";
import {
  getTeamByPage,
  addTeam,
  selectUserListByTeam,
  getUserByTeamId,
  addTeamUser,
} from "@/api/baseData/team";
import {
  addWoRaw,
  getWoRawByPage,
  updateWoRawStatus,
} from "@/api/product/woRaw";
import {
  addWoRawRel,
  startWoRaw,
  insertWoRawRel,
  endWoRaw,
  pauseWoRaw,
} from "@/api/product/woRawRel";
import { getWoRawSubByPage } from "@/api/product/woRawSub";
import {
  getWoRawSubRelFaultByPage,
  addWoRawSubRelFault,
} from "@/api/product/woRawSubRelFault";

import {
  getWoTagValueByPage,
  addWoTagValue,
  delWoTagValue,
  updateWoTagValue,
} from "@/api/product/woTagValue";

import { getUserNameByTeamId } from "@/api/baseData/team";
import { getFaultTypeByPage } from "@/api/product/faultType";
import { getEquipAndProcessByWo } from "@/api/baseData/procedures";
import {
  addProceduresEquipmentConfigs,
  getProceduresEquipmentConfigByPage,
  getEquipAndProceduresByWo,
} from "@/api/baseData/proceduresEquipmentConfig";
import XEUtils, { first } from "xe-utils";

import WoRaw from "./base/woRaw.vue";
import WorkOrder from "./base/workOrderHead.vue";
import WoSubFault from "./base/woSubFault.vue";
import WoTagValue from "./base/woTagValue.vue";
import WoSub from "./base/woSub.vue";
import emitter from "@/utils/eventMitt";
import vueEasyPrint from "vue-easy-print";
import "./print/premixLabel.less";
import VueQrcode from "vue-qrcode";
// 模拟后端接口
const getApiList = (quert) => {
  let idKey = 1;
  return new Promise((resolve) => {
    setTimeout(() => {
      const list = XEUtils.range(0, XEUtils.random(1, 10)).map(() => {
        return {
          value: idKey++,
          label: `选项${idKey}_${quert.searchValue}`,
        };
      });
      resolve(list);
    }, 200);
  });
};
export default {
  components: {
    WoRaw,
    WorkOrder,
    WoSubFault,
    WoTagValue,
    WoSub,
    vueEasyPrint,
    VueQrcode,
  },
  async created() {
    this.remoteConfig = {
      queryMethod: async ({ searchValue }) => {
        const result = await getTeamByPage({
          total: 2,
          pageSize: 10,
          currentPage: 1,
        });
        this.opts1 = result.data.records;
      },
    };
    this.remoteConfig2 = {
      queryMethod: async ({ searchValue }) => {
        /**
         * 如果班组人员不够
         */
        if (null == this.formData.teamId || "" == this.formData.teamId) {
          VxeUI.modal.message({
            content: "请先选择班组",
            status: "warning",
          });
          return;
        }
        const result = await getUserNameByTeamId({
          total: 2,
          pageSize: 10,
          currentPage: 1,
          id: this.formData.teamId,
        });
        this.opts2 = result.data;
      },
    };
    const result = await getFaultTypeByPage({
      currentPage: 1,
      pageSize: 200,
    });
    this.faultTypeListRender.options = result.data.records
      .filter((item) => item.id != null || item.name != "")
      .map((item) => {
        return {
          value: item.id,
          label: item.name,
        };
      });
    // console.log(
    //   this.faultTypeListRender.options,
    //   "===>this.faultTypeListRender.options"
    // );
  },
  async mounted() {
    const { wo, proceduresNum, type } = this.$route.query;
    if (undefined != wo) {
      this.formData.workNo = wo;
      // this.teamOptions.loading = true;

      let result2 = await getWorkOrderByCode({ wo: wo });
      console.log("===>result2=====", result2);

      this.formData.materialCode = result2.data.materialCode;
      this.formData.materialName = result2.data.materialName;
      this.formData.planEndTime = result2.data.planEndTime;
      this.formData.qty = result2.data.qty;
      let result = await getEquipAndProceduresByWo({
        sequence: proceduresNum,
        woType: type,
      });

      //根据工单号获取工单
      this.equipmentOptions.options = result.data.equipmentConfigVoList.map(
        (item) => {
          return { label: item.name, value: item.id };
        }
      );
      this.teamOptions.options = result.data.teamVoList.map((item) => {
        return { label: item.name, value: item.id };
      });
      this.processRelVo = result.data.processRelVo;
      this.teamOptions.loading = false;
      this.formData.proceduresName = this.processRelVo.proceduresName;
    }

    this.$nextTick(() => {
      // 现在可以安全地访问 this.$refs.myInput 或 this.$refs.myComponent
      this.emitter.on("workOrder", (formData) => {
        this.formData = formData;
        this.formData.workNo = formData.workNo;
        this.woRawSub.wo = formData.workNo;
        // this.$refs.gridRef2.$refs.gridRef2.commitProxy("reload");
        console.log("===>this.formData==", formData);
        // this.$refs.gridRef2.$refs.gridRef2.commitProxy("reload");
      });
    });
  },
  data() {
    const insertRecords = [];

    const woSubRows = [];
    //子卷信息
    const gridOptions = {
      sortConfig: {
        remote: true,
      },
      loading: false,
      stripe: true,
      showOverflow: true,
      showFooter: true,

      columnConfig: {
        resizable: true,
        drag: true,
      },
      columnDragConfig: {
        trigger: "cell",
        showIcon: false,
        showGuidesStatus: true,
      },
      rowConfig: {
        isHover: true,
      },
      resizableConfig: {
        isDblclickAutoWidth: true,
      },
      pagerConfig: {
        total: 0,
        currentPage: 1,
        pageSize: 10,
      },
      formConfig: {
        data: {
          name: "",
          role: "",
          sex: "",
          num: "",
          address: "",
        },
        items: [
          {
            field: "name",
            title: "名称",
            span: 8,

            itemRender: { name: "VxeInput", props: { clearable: true } },
          },

          {
            field: "createTime",
            title: "时间",
            span: 8,

            itemRender: {
              name: "VxeDatePicker",
              props: {
                multiple: true,
              },
            },
          },

          {
            collapseNode: true,
            align: "right",
            span: 8,
            itemRender: {
              name: "VxeButtonGroup",
              options: [
                { type: "submit", content: "搜索", status: "primary" },
                { type: "reset", content: "重置" },
              ],
            },
          },
        ],
      },
      columns: [
        { type: "checkbox", width: 60 },
        { field: "seq", type: "seq", width: 70 },

        { field: "wo", title: "工单号", sortable: true, width: 180 },
        { field: "serialNo", title: "序列号", sortable: true, width: 180 },
        {
          field: "length",
          title: "长度",
          sortable: true,
          width: 180,
        },
        {
          field: "rawType",
          title: "类型",
          sortable: true,
          width: 180,
        },
        { field: "createTime", title: "创建时间", width: 180 },
        {
          field: "active",
          title: "操作",
          fixed: "right",
          width: 600,
          slots: { default: "active" },
        },
      ],
      scrollX: {
        gt: 0,
        enabled: true,
      },
      scrollY: {
        gt: 0,
        enabled: true,
      },
      proxyConfig: {
        sort: true,
        form: true,
        ajax: {
          query: async ({ page, sorts, form }) => {
            console.log(page, sorts, form, "----");

            // 默认接收 Promise<{ result: [], page: { total: 100 } }>
            let result = await getWoRawSubByPage({
              ...page,
              wo: this.formData.workNo,
            });
            return {
              result: result.data.records,
              page: {
                total: result.data.total,
              },
            };
          },
        },
      },
    };

    const gridOptions5 = {
      editConfig: {
        trigger: "click",
        mode: "cell",
        showStatus: true,
      },
      height: "100%",
      sortConfig: {
        remote: true,
      },
      loading: false,
      stripe: true,
      showOverflow: true,
      showFooter: true,

      columnConfig: {
        resizable: true,
        drag: true,
      },
      columnDragConfig: {
        trigger: "cell",
        showIcon: false,
        showGuidesStatus: true,
      },
      rowConfig: {
        isHover: true,
      },
      resizableConfig: {
        isDblclickAutoWidth: true,
      },
      pagerConfig: {
        total: 0,
        currentPage: 1,
        pageSize: 10,
      },

      formConfig: {
        data: {
          name: "",
          role: "",
          sex: "",
          num: "",
          address: "",
        },
        items: [
          {
            field: "name",
            title: "名称",
            span: 8,

            itemRender: { name: "VxeInput", props: { clearable: true } },
          },

          {
            field: "createTime",
            title: "时间",
            span: 8,

            itemRender: {
              name: "VxeDatePicker",
              props: {
                multiple: true,
              },
            },
          },

          {
            collapseNode: true,
            align: "right",
            span: 8,
            itemRender: {
              name: "VxeButtonGroup",
              options: [
                { type: "submit", content: "搜索", status: "primary" },
                { type: "reset", content: "重置" },
              ],
            },
          },
        ],
      },
      columns: [
        { type: "checkbox", width: 60 },
        { field: "seq", type: "seq", width: 70 },

        {
          field: "rawCode",
          title: "物料编号",
          sortable: true,
          width: 180,
        },

        {
          field: "dataLossValue",
          title: "数采损耗值",
          sortable: true,
          width: 180,
        },

        {
          field: "actualLossValue",
          title: "实际损耗值",
          sortable: true,
          width: 180,
          editRender: { name: "VxeNumberInput", props: { type: "float" } },
        },

        // {
        //   field: "startTime",
        //   title: "计划开工时间",
        //   sortable: true,
        //   width: 180,
        // },
        { field: "createTime", title: "创建时间", width: 180 },
        {
          field: "active",
          title: "操作",
          fixed: "right",
          width: 300,
          slots: { default: "active" },
        },
      ],
      scrollX: {
        gt: 0,
        enabled: true,
      },
      scrollY: {
        gt: 0,
        enabled: true,
      },
      proxyConfig: {
        // props: {
        //   result: 'result', // 配置响应结果列表字段
        //   total: 'page.total' // 配置响应结果总页数字段
        // },

        sort: true,
        form: true,
        ajax: {
          query: async ({ page, sorts, form }) => {
            console.log(page, sorts, form, "----");

            // 默认接收 Promise<{ result: [], page: { total: 100 } }>
            let result = await getWoRawByPage({
              ...page,
              wo: this.woRawSub.wo ? this.woRawSub.wo : this.formData.workNo,
              subId: this.woRawSub.id ? this.woRawSub.id : null,
            });
            this.woRawSub = { id: null, wo: null };
            return {
              result: result.data.records,
              page: {
                total: result.data.total,
              },
            };
          },
        },
      },
    };
    const tableData = [
      // {
      //   id: 10000,
      //   workNo: "workNo",
      //   motherRoll: "Test1",
      //   sonRoll: "sonRoll",
      //   materilNo: "mp3",
      //   materilDesc: 1024,
      //   weight: "10",
      //   unit: "千克",
      // },
    ];
    const tableData2 = [
      // {
      //   id: 10000,
      //   rawCode: "workNo",
      //   batchCode: "Test1",
      //   wo: "sonRoll",
      //   status: "mp3",
      // },
    ];
    const rowConfig = {
      keyField: "id",
    };
    const treeConfig = {
      transform: true,
      rowField: "id",
      parentField: "parentId",
    };
    const editConfig = {
      trigger: "click",
      mode: "cell",
      showStatus: true,
    };
    const formData = {
      //二维码
      scanBarcode: "",
      workstationId: "", //工位信息
      workNo: "", //工单信息
      proceduresName: "工序信息",
      equipmentId: null, //取下拉菜单第一个需要 置为NULL
      teamId: null, //取下拉菜单第一个需要 置为NULL
      worker: "",
      remark: "",
      rawMaterial: "",
      rollNums: "",
      materialCode: "",
      materialName: "",
      weight: "",
      planEndTime: "",
    };
    const formRules = {
      scanBarcode: [{ required: true, message: "必须填写" }],
      workstationId: [{ required: true, message: "必须填写" }],
      workNo: [
        {
          required: true,
          pattern: "\\d{2}-\\d{5}",
          message: "字母开头5~10位数",
        },
      ],
      teamId: [{ required: true, message: "必须填写" }],
      rawMaterial: [{ required: true, message: "必须填写" }],
      // rawMaterial: [
      //   {
      //     required: true,
      //     pattern: "^[a-zA-Z]\\w{5,7}$",
      //     message: "字母开头5~10位数",
      //   },
      // ],
      // role: [{ required: true, message: "必须填写" }],
    };
    const showPopup = false;
    const showPopup2 = false;
    const showPopup3 = false;
    const showPopup4 = false;
    const modalOptions = {
      title: "在弹窗中使用表单",
      width: 800,

      escClosable: true,
      resize: true,
      showMaximize: true,
      //禁止拖动
      draggable: true,
    };
    const modalOptions2 = {
      title: "在弹窗中使用表单",
      width: 800,

      escClosable: true,
      resize: true,
      showMaximize: true,
      //禁止拖动
      draggable: true,
    };
    const modalOptions3 = {
      title: "在弹窗中使用表单",
      width: 800,

      escClosable: true,
      resize: true,
      showMaximize: true,
      //禁止拖动
      draggable: true,
    };
    const modalOptions4 = {
      title: "填写实际损耗值",
      width: "80%",
      height: 600,
      escClosable: true,
      resize: true,
      showMaximize: true,
      //禁止拖动
      draggable: true,
    };
    const formOptions = {
      data: {
        length: "",
        rawType: "",
      },
      rules: {
        length: [{ required: true, message: "必填" }],
        rawType: [{ required: true, message: "必填" }],

        // role: [{ required: true, message: "角色必填" }],
        // sex: [{ required: true, message: "性别必选" }],
        // age: [
        //   { required: true, message: "年龄必填" },
        //   { type: "number", min: 18, max: 46, message: "年龄范围18~46" },
        // ],
      },
      items: [
        {
          field: "length",
          title: "长度",
          span: 24,
          itemRender: { name: "VxeInput" },
        },
        {
          field: "rawType",
          title: "物料类型",
          span: 24,
          itemRender: {
            name: "VxeSelect",
            props: {
              // multiple: true,
              clearable: true,
            },
            options: [
              {
                value: "一面",
                label: "一面",
              },
              {
                value: "二面",
                label: "二面",
              },
              {
                value: "三面",
                label: "三面",
              },
            ],
          },
        },
        {
          align: "center",
          span: 24,
          itemRender: {
            name: "VxeButtonGroup",
            options: [
              { type: "submit", content: "提交", status: "primary" },
              { type: "reset", content: "重置" },
            ],
          },
        },
      ],
    };
    const formOptions2 = {
      data: {
        id: 0,
        status: "",
      },
      rules: {
        // length: [{ required: true, message: "必填" }],
        // role: [{ required: true, message: "角色必填" }],
        // sex: [{ required: true, message: "性别必选" }],
        // age: [
        //   { required: true, message: "年龄必填" },
        //   { type: "number", min: 18, max: 46, message: "年龄范围18~46" },
        // ],
      },
      items: [
        {
          field: "status",
          title: "状态",
          span: 24,
          itemRender: {
            name: "VxeSelect",
            options: [
              { label: "已消耗", value: "已消耗" },
              { label: "未消耗", value: "未消耗" },
            ],
          },
        },
        {
          align: "center",
          span: 24,
          itemRender: {
            name: "VxeButtonGroup",
            options: [
              { type: "submit", content: "提交", status: "primary" },
              { type: "reset", content: "重置" },
            ],
          },
        },
      ],
    };
    // const opts3 = [
    //   { label: "女", value: "Women" },
    //   { label: "男", value: "Man" },
    // ];
    const faultTypeListRender = {
      name: "VxeSelect",
      props: {
        multiple: true,
        clearable: true,
      },
      options: [],
    };
    const formOptions3 = {
      data: {
        id: 0,
        startMetre: "",
        endMetre: "",
        faultTypeList: "",
        woRawSubId: 0,
      },
      rules: {
        // length: [{ required: true, message: "必填" }],
        // role: [{ required: true, message: "角色必填" }],
        // sex: [{ required: true, message: "性别必选" }],
        // age: [
        //   { required: true, message: "年龄必填" },
        //   { type: "number", min: 18, max: 46, message: "年龄范围18~46" },
        // ],
      },
      items: [
        {
          field: "startMetre",
          title: "米数起始位置",
          span: 24,
          itemRender: { name: "VxeInput" },
        },
        {
          field: "endMetre",
          title: "米数结束位置",
          span: 24,
          itemRender: { name: "VxeInput" },
        },
        {
          field: "faultTypeList",
          title: "缺陷类型",
          span: 24,
          itemRender: faultTypeListRender,
        },
        {
          align: "center",
          span: 24,
          itemRender: {
            name: "VxeButtonGroup",
            options: [
              { type: "submit", content: "提交", status: "primary" },
              { type: "reset", content: "重置" },
            ],
          },
        },
      ],
    };
    const opts1 = [];
    const opts2 = [];

    const remoteConfig = {};
    const remoteConfig2 = {};
    const woRawSub = { id: 0, wo: "" };

    // const equipmentConfigVoList = [{ id: 0, name: "" }];
    const processRelVo = { id: 0, proceduresName: "" };
    const equipmentOptions = {
      loading: false,
      placeholder: "请选择设备",
      defaultConfig: {
        selectMode: "last",
      },
      options: [],
    };
    const teamOptions = {
      loading: false,
      placeholder: "请选择班组",
      defaultConfig: {
        selectMode: "first",
      },
      options: [],
    };
    return {
      activeTab: "1",
      border: true,
      titleBackground: false,
      formData,
      formRules,
      tableData,
      tableData2,
      rowConfig,
      treeConfig,
      editConfig,
      gridOptions,
      gridOptions5,
      showPopup,
      modalOptions,
      formOptions,
      insertRecords,
      showPopup2,
      modalOptions2,
      formOptions2,

      showPopup3,
      modalOptions3,
      showPopup4,
      modalOptions4,
      faultTypeListRender,
      formOptions3,

      loading: false,

      val1: null,
      opts1,
      opts2,
      remoteConfig,
      remoteConfig2,
      woRawSub,
      // equipmentConfigVoList,
      processRelVo,
      equipmentOptions,
      teamOptions,
      emitter: emitter,
      woSubRows,
      size: 200,
    };
  },

  methods: {
    removeRow(row) {
      const $grid = this.$refs.gridRef2;
      if ($grid) {
        $grid.remove(row);
        VxeUI.modal.message({
          content: "数据已删除",
          status: "success",
        });
      }
    },
    async pushEvent() {
      const $table = this.$refs.tableRef;
      if ($table) {
        const record = {
          name: `Name_${new Date().getTime()}`,
        };
        const { row: newRow } = await $table.insertAt(record, -1);
        // 激活并自动聚焦第一个可编辑列
        $table.setEditRow(newRow, true);
      }
    },
    async insertEvent() {
      const $table = this.$refs.tableRef;
      if ($table) {
        const record = {
          name: `Name_${new Date().getTime()}`,
        };
        const { row: newRow } = await $table.insertAt(record, 2);
        $table.setEditCell(newRow, "name");
      }
    },
    async insertRow(row) {
      const $table = this.$refs.tableRef;
      if ($table) {
        const record = {
          name: `Name_${new Date().getTime()}`,
        };
        const { row: newRow } = await $table.insertAt(record, row);
        $table.setEditCell(newRow, "name");
      }
    },
    async insertChild(row) {
      const $table = this.$refs.tableRef;
      if ($table) {
        const record = {
          name: `Name_${new Date().getTime()}`,
        };
        const { row: newRow } = await $table.insertChild(record, row);
        $table.setEditCell(newRow, "name");
      }
    },
    async inputEnter(params) {
      let paras = params.split("@");
      if (paras.length < 3) {
        VxeUI.modal.message({ content: "需要包含三个@", status: "error" });
      } else {
        //订单@物料@数量@开工日期@完工日期
        try {
          const result = await addWorkOrder({
            wo: paras[0],
            qty: paras[2],
            type: "涂布",
            materialCode: paras[1],
          });
          console.log("====>result===", result);

          const result2 = await getEquipAndProceduresByWo({
            sequence: result.data.proceduresNum,
            woType: "涂布",
          });
          this.formData.workNo = paras[0];
          this.formData.materialCode = paras[1];
          this.formData.qty = paras[2];
          this.formData.planEndTime = paras[4];
          //  this.formData.rawMaterial = paras[1]
          this.equipmentOptions.options =
            result2.data.equipmentConfigVoList.map((item) => {
              return { label: item.name, value: item.id };
            });
          this.teamOptions.options = result2.data.teamVoList.map((item) => {
            return { label: item.name, value: item.id };
          });
          this.processRelVo = result2.data.processRelVo;

          this.formData.proceduresName = this.processRelVo.proceduresName;
          // localStorage.setItem("MES_COAT_WO", JSON.stringify(paras[0]));
          // console.log("保存成功", JSON.stringify(this.formOptions.data));
          VxeUI.modal.message({ content: "保存成功", status: "success" });
          // const $grid = this.$refs.gridRef.commitProxy("reload");
          this.loading = false;
          this.showPopup = false;

          // debugger;
          console.log(this.formData.workNo, "===> this.formData.workNo");
          this.formData.scanBarcode = "";
        } catch (error) {
          this.loading = false;
        } finally {
          const $grid =
            this.$refs.gridRef2.$refs.gridRef2.commitProxy("reload");
        }
      }
    },

    async rawInputEnter(params) {
      let paras = params.split(";");
      if (paras.length < 2) {
        VxeUI.modal.message({ content: "需要包含两个;", status: "error" });
      } else {
        //物料编号+批次编号+数量
        try {
          // const value = localStorage.getItem("MES_COAT_WO");
          const result = await addWoRaw({
            rawCode: paras[0],
            batchCode: paras[1],
            wo: this.formData.workNo,
            qty: paras[2],
          });
          // console.log("保存成功", JSON.stringify(this.formOptions.data));

          let result2 = await getWoRawByPage({
            currentPage: 1,
            pageSize: 100,
            // wo: row.wo,
          });
          this.tableData2 = result2.data.records;
          VxeUI.modal.message({ content: "保存成功", status: "success" });
          const $grid = this.$refs.gridRef.commitProxy("reload");
          const $grid2 = this.$refs.gridRef2.commitProxy("reload");
          this.loading = false;
          this.showPopup = false;
        } catch (error) {
          this.loading = false;
        } finally {
          const $grid = this.$refs.gridRef2.commitProxy("reload");
        }
      }
    },
    async addEvent() {
      const $grid = this.$refs.gridRef2.$refs.gridRef2;
      if (this.formData.workNo == "" || this.formData.workNo == undefined) {
        VxeUI.modal.message({
          content: "请先输入工单信息",
          status: "error",
        });
      } else {
        if ($grid) {
          const record = {
            rawCode: ``,
            wo: this.formData.workNo,
            qty: 1,
            status: "未消耗",
            active: "",
          };
          const { row: newRow } = await $grid.insert(record);
          // 激活不自动聚焦
          $grid.setEditRow(newRow);

          // 激活并自动聚焦
          // $grid.setEditRow(newRow, 'name')
          // 激活并自动聚焦
          // $grid.setEditCell(newRow, 'name')
        }
      }
    },
    async saveEvent() {
      const $grid = this.$refs.gridRef2.$refs.gridRef2;
      console.log($grid, "-----$grid---");
      if ($grid) {
        const insertRecords = $grid.getInsertRecords();
        const result = await addWoRaws(insertRecords);
        $grid.commitProxy("reload");
        // VxeUI.modal.alert(`新增：${insertRecords.length} 行`);
      }
    },
    async saveLossEvent() {
      const $grid = this.$refs.gridRef2;
      if ($grid) {
        const insertRecords = $grid.getUpdateRecords();
        console.log("===>insertRecords", insertRecords);
        // const result = await addWoRaws(insertRecords);
        // this.$refs.gridRef2.commitProxy("reload");
        // VxeUI.modal.alert(`新增：${insertRecords.length} 行`);
      }
    },
    getInsertEvent() {
      const $table = this.$refs.tableRef;
      if ($table) {
        const insertRecords = $table.getInsertRecords();
        VxeUI.modal.message({ content: "需要包含三个;", status: "warning" });
      }
    },
    parameterAcquisition() {
      this.showPopup = true;
      console.log("===>猜测是");
    },
    async resetEvent() {},
    async searchRawData(row) {
      console.log("==row==>", row);
      // let result = await getWoRawByPage({
      //   currentPage: 1,
      //   pageSize: 100,
      //   wo: row.wo,
      //   subId: row.id,
      // });
      this.woRawSub = row;
      // this.tableData2 = result.data.records;
      this.activeTab = "2";
      const $grid2 = this.$refs.gridRef2.commitProxy("reload");
      console.log(this.tableData);
    },
    async searchFaultData(row) {
      console.log("==row==>", row);
      // let result = await getWoRawByPage({
      //   currentPage: 1,
      //   pageSize: 100,
      //   wo: row.wo,
      //   subId: row.id,
      // });
      this.woRawSub = row;
      // this.tableData2 = result.data.records;
      this.activeTab = "3";
      const $grid2 = this.$refs.gridRef3.commitProxy("reload");
      console.log(this.tableData);
    },
    async recordDefective(row) {
      this.showPopup3 = true;
      /**
       * 等会
       */
      this.modalOptions3.title = "子卷的缺陷信息";
      this.formOptions3.data.woRawSubId = row.id;
    },
    async submitEvent() {
      console.log("====>submitEvent===>");
      const value = localStorage.getItem("MES_COAT_WO");
      console.log("====>", this.formOptions.data);
      this.showPopup = false;
      try {
        await insertWoRawRel({
          wo: this.formData.workNo,
          ...this.formOptions.data,
          type: "涂布",
        });
      } catch (error) {
      } finally {
        const $grid = this.$refs.gridRef3.$refs.gridRef.commitProxy("reload");
      }
    },
    async updateRow(row) {
      console.log("===>", row);
    },
    async updateWoRawStatus(row) {
      //这个需要赋值
      this.formOptions2.data = row;
      this.showPopup2 = true;
    },
    async submitEvent2() {
      console.log("===>submitEvent2", this.formOptions2.data);
      this.showPopup2 = false;
      try {
        await updateWoRawStatus({
          ...this.formOptions2.data,
        });
      } catch (error) {
      } finally {
        const $grid = this.$refs.gridRef2.commitProxy("reload");
      }
    },
    /**
     * 提交不良记录
     */
    async submitEvent3() {
      this.showPopup3 = false;
      try {
        await addWoRawSubRelFault({ ...this.formOptions3.data });
      } catch (error) {
      } finally {
        const $grid3 = this.$refs.gridRef3.commitProxy("reload");
      }
      // const result = await addWoRawSubRelFault({ ...this.formOptions3.data });
      // console.log("==this.formOptions3.data==>", this.formOptions3.data);
    },
    async startWoRawClick() {
      console.log("====>startWoRaw====>");
      // const value = localStorage.getItem("MES_COAT_WO");
      try {
        await startWoRaw({
          wo: this.formData.workNo,
          ...this.formOptions.data,
          type: "涂布",
        });
        await this.freshWorkOrder();
      } catch (error) {
      } finally {
        this.$refs.gridRef3.$refs.gridRef.commitProxy("reload");
      }
    },
    async pauseWoRawClick() {
      try {
        await pauseWoRaw({
          wo: this.formData.workNo,
          ...this.formOptions.data,
          type: "预混",
        });
        /**
         * 完工之后刷新
         */
        await this.freshWorkOrder();
      } catch (error) {
      } finally {
        // const $grid = this.$refs.gridRef.commitProxy("reload");
      }
    },
    async endWoRawClick() {
      console.log("====>endWoRaw====>");
      // if ("" == this.formData.workNo) {
      //   VxeUI.modal.message({ content: "请先录入工单;", status: "warning" });
      // } else {
      //   this.showPopup4 = true;
      // }
      // const value = localStorage.getItem("MES_COAT_WO");
      try {
        await endWoRaw({
          wo: this.formData.workNo,
          ...this.formOptions.data,
          type: "混胶",
        });
        await this.freshWorkOrder();
      } catch (error) {
      } finally {
        this.$refs.gridRef3.$refs.gridRef.commitProxy("reload");
        // const $grid = this.$refs.gridRef.commitProxy("reload");
      }
    },
    async saveActualLossValue() {
      console.log("===>保存实际值");
      console.log(this.$refs.gridRef5.getFullData());
      try {
        await updateWoRawActualLossValue(this.$refs.gridRef5.getFullData());
        await endWoRaw({
          wo: this.formData.workNo,
          ...this.formOptions.data,
          type: "胶水制备",
        });
        VxeUI.modal.message({ content: "操作成功;", status: "success" });
      } catch (error) {
      } finally {
        const $grid = this.$refs.gridRef2.commitProxy("reload");
      }
    },
    labelPrintClick() {
      this.woSubRows = this.$refs.gridRef3.$refs.gridRef.getFullData();
      console.log(this.woSubRows, "===>this.woSubRows");
      // console.log($grid, "===>grid====");
      setTimeout(() => {
        this.$refs.printRef.print();
      }, 500);
    },
    fresh() {
      this.$refs.gridRef2.$refs.gridRef2.commitProxy("reload");
    },
  },
};
</script>
<style lang="scss" scoped>
.content {
  height: calc(100vh - 130px);
}
</style>
